package io.gitee.wiqer.hard;

import org.junit.Test;

public class SolutionNC128_MaxWater {
    /**
     * max water
     * @param arr int整型一维数组 the array
     * @return long长整型
     */
    public long maxWater (int[] arr) {
        // write code here
        int[] arrWater=new int[arr.length];
        int leftMax=arr[0];
        int rightMax=arr[arr.length-1];
        int leftMaxIndex=0;
        /**
         * 左侧的水往左流，右边大水漫灌
         */
        for (int i = 0; i < arr.length; i++) {
           if(i==0||i==arr.length - 1){
               arrWater[i]=0;
           }
           if(leftMax<arr[i]){
               leftMax=arr[i];
               leftMaxIndex=i;
           }else {
               arrWater[i]=leftMax-arr[i];
           }
        }
        /**
         * 右侧的水往右流
         */
        for (int i = arr.length-1; i >= 0; i--) {
            if(i<=leftMaxIndex){
                break;
            }
            if(rightMax<arr[i]){
                rightMax=arr[i];
                arrWater[i]=0;
            }else {
                arrWater[i]=Math.min(arrWater[i],rightMax-arr[i]) ;
            }
        }
        long sum = 0;
        for (int i = arrWater.length - 1; i >= 0; i--) {
            sum+=arrWater[i];
        }
       return sum;
    }
    @Test
    public void test(){
        int[] arr={3,1,2,5,2,4};
        System.out.println(maxWater(arr)) ;
        int[] arr2={4,5,1,3,2};
        System.out.println(maxWater(arr2)) ;
        int[] arr3={6,1,1,1,1,1,1,6};
        System.out.println(maxWater(arr3)) ;
        int[] arr4={6,1,1,1,11,1,69,1,1,6};
        System.out.println(maxWater(arr4)) ;

    }
}
